/***
 * 递归寻找对应value的optionitem
 * @param options 选项列表
 * @param value 对应值
 * @returns 选项{label:string,value:any}
 */
import type { ProFormColType } from "../../interface";

export const findOptionItems = (
  options: NonNullable<ProFormColType<any>["options"]>,
  value: any
) => {
  if (!options?.length) {
    return;
  }
  const arr = [...options];
  // const items = [];
  while (arr.length) {
    const option = arr.shift()!;

    if (option?.options?.length) {
      arr.push(...option.options);
    } else if (option?.value === value) {
      return option;
    }
  }

  // return items;
};

export const getValue = (
  obj: Record<string, any>,
  path: string | number | (string | number)[]
) => {
  if (typeof path === "string" || typeof path === "number") {
    return obj[path];
  }
  if (Array.isArray(path)) {
    return path.reduce((acc, cur) => acc?.[cur], obj);
  }
  return undefined;
};
export const setValue = (
  obj: Record<string, any>,
  path: string | number | (string | number)[],
  val: any
) => {
  if (typeof path === "string" || typeof path === "number") {
    obj[path] = val;
    return;
  }
  if (Array.isArray(path)) {
    path.reduce((acc, cur, index) => {
      if (index === path.length - 1) {
        acc[cur] = val;
      } else if (acc[cur] === undefined) {
        acc[cur] = {};
      }
      return acc[cur];
    }, obj);
  }
};

export const modalVal = (
  obj: Record<string, any>,
  path: string | number | (string | number)[]
) => {
  return {
    get() {
      return getValue(obj, path);
    },
    set(val: any) {
      setValue(obj, path, val);
    },
  };
};
